<?php
/**
 * erp-FBA每日库存报表(Amazon每日库存同步至erp)
 * fab:inventory
 */

namespace App\Logic\SalesReport;

use App\Models\Amazon\FBAMYIInventory;
use App\Models\Amazon\FbaReservedInventory;
use App\Models\Basics\AmazonCountry;
use App\Models\Basics\SysArea;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysICountry;
use App\Models\Product\ProductAmazonSku;
use App\Models\Product\ProductSku;
use App\Models\SalesReport\FBAInventory as SrFBAInventoryModel;
use Illuminate\Support\Facades\DB;
class SrFBAInventory
{
    public static function init(){

        try{
            //erp-FBA每日库存
            SrFBAInventoryModel::query()->truncate();

            $fanEUSku = [];
            $fanCASku = [];
            $countryIdFR = SysCountry::getIdByCountry('FR');
            $countryIdDE = SysCountry::getIdByCountry('DE');
            $countryIdUK = SysCountry::getIdByCountry('UK');
            //泛欧国家id
            $countryIdsForFanEU = array_keys(AmazonCountry::options(['fan_eu' => 1])->toArray());

            //EU站点下的国家id
            $euAreaId = SysArea::getSysAreaIdByArea('EU');
            $countryIdsForEU = SysICountry::getCountryIdsByAreaId($euAreaId)->toArray();

            //排除EU站点国家('NL'荷兰,'PL'波兰,'SE'瑞典,'TR土耳其','BE比利时')
            $countryIdsForEUNoTotalInventory = SysICountry::getEuCountryIdsForNoTotalInventory($euAreaId)->toArray();
            //排除US站点国家('MX'墨西哥,'BR'巴西)
            $countryIdsForNaNoTotalInventory = SysICountry::getNaCountryIdsForNoTotalInventory()->toArray();

            DB::beginTransaction();
            $pSkuArr = [];
            $areaArr = [];
            $priceArr = [];
            //Amazon-FBA每日库存
            FBAMYIInventory::query()->orderBy('created_at')
                ->chunk(800, function ($items) use (&$fanEUSku,&$fanCASku,&$pSkuArr,&$areaArr,&$priceArr,$countryIdDE,$countryIdUK,$countryIdFR,$countryIdsForNaNoTotalInventory,$countryIdsForFanEU,$countryIdsForEU,$countryIdsForEUNoTotalInventory){
                    foreach($items as $item){

                        if (in_array($item->sku, ['AM05075-AMUK2-FBA102','AM05075-AMUK-FBA102'])) continue;
                        if (intval($item->country_id) == $countryIdUK){
                            if (in_array($item->sku, ['AM04207-AMEU-FBA105'])) continue;
                        }
                        if (intval($item->country_id) == $countryIdUK && intval($item->account_id) == 35) {
                            $count = SrFBAInventoryModel::query()
                                ->where('country_id',$item->country_id)
                                ->where('account_id',$item->account_id)
                                ->where('fnsku',$item->fnsku)
                                ->where('asin',$item->asin)
                                ->count(); //验证UK库存,(fnsku + sain)相同时,只记录一次库存
                            if ($count > 0) continue;
                        }

                        if(in_array($item->country_id,$countryIdsForNaNoTotalInventory)) continue;

                        if(in_array($item->country_id,$countryIdsForEU)){
                            if(in_array($item->country_id,$countryIdsForEUNoTotalInventory)) continue;

                            $currentCount = ProductAmazonSku::query()
                                ->where('country_id',$item->country_id)
                                ->where('seller_sku',$item->sku)
                                ->count();
                            $ukCount = ProductAmazonSku::query()
                                ->where('country_id',$countryIdUK)
                                ->where('seller_sku',$item->sku)
                                ->count();
                            if($currentCount == 0 && $ukCount > 0){
                                continue;
                            }
                            if($item->sku == 'AM05024-AMEU-FBA23'){
                                continue;
                            }
                            if($item->country_id == $countryIdFR){
                                if(in_array($item->sku,['38IT-AM02076','38IT-AM01347','38IT-AM03091',
                                    '38IT-AM02744', '38IT-AM02745','38IT-AM04206','38IT-AM02091',
                                    'AM01313-AMEU-FBA38','AM01345-AMEU-FBA38','AM04204-AMEU-FBA38',
                                    'AM02747-AMEU-FBA38','AM01312-AMEU-FBA38','66IT-AM01309','66IT-AM02746',
                                    '66ES-AM01489'])){
                                    continue;
                                }
                            }
                            if($item->country_id != $countryIdDE){
                                if(in_array($item->sku,['23DE-AM01187','23DE-AM01192','23DE-AM01193',
                                    '23DE-AM01313','23DE-AM01348','23DE-AM01352','23DE-AM01463','23DE-AM01464',
                                    '23DE-AM02078','23DE-AM02079','23DE-AM02091','23DE-AM02092','23DE-AM02745',
                                    '23DE-AM03218','23DE-AM03219','23DE-AM04204','23DE-AM04205','23DE-AM04206',
                                    '23DE-N-AM01325','23DE-N-AM02082','23DE-N-AM03217','23DE-N2-AM02077'])){
                                    continue;
                                }
                            }
                        }

                        //验证泛欧
                        if(in_array($item->country_id,$countryIdsForFanEU)){
                            $fanEuKey = $item->account_id.'_'.$item->fnsku; //泛欧
                            if(!array_key_exists($fanEuKey,$fanEUSku)){
                                $fanEUSku[$fanEuKey] = true;
                            }else{
                                continue; //排除账号中重复的fnsku。（fnsku存在2个及2个以上，则为泛欧。）
                            }
                        }
                        //验证CA
                        if(in_array($item->country_id,[2])){ //CA
                            $fanCaKey = $item->account_id.'_'.$item->fnsku;
                            if(!array_key_exists($fanCaKey,$fanCASku)){
                                $fanCASku[$fanCaKey] = true;
                            }else{
                                continue; //排除账号中重复的fnsku。（fnsku存在2个及2个以上。）
                            }
                        }

                        if(!$item->area_id){
                            if(!array_key_exists($item->country_id,$areaArr)){
                                $areaArr[$item->country_id] = SysCountry::getAreaIdByCountryId($item->country_id);
                            }
                            $areaId = $areaArr[$item->country_id];
                        }else{
                            $areaId = $item->area_id;
                        }

                        if(!$item->psku_id){
                            if(!array_key_exists($item->psku_id,$pSkuArr)){
                                $pSkuArr[$item->psku_id] = ProductAmazonSku::getValueByCode($item->sku,'psku_id');
                            }
                            $pSkuId = $pSkuArr[$item->psku_id];
                        }else{
                            $pSkuId = $item->psku_id;
                        }

                        //可发库存
                        $fulfillableQuantity = $item->afn_fulfillable_quantity;

                        //保留库存 (运输数量+处理数量)
                        $fbaReservedInventory = FbaReservedInventory::getReservedInventory($item->sku, $item->country_id);//保留库存
                        $reservedQuantity = $fbaReservedInventory->reserved_quantity ?? 0;

                        //备货提货时参考的总库存 (可发库存+保留库存)
                        $quantity = $fulfillableQuantity + $reservedQuantity;

                        //FBA在途库存 (FBA在途未发出数量 + FBA在途运输数量 + FBA在途接收数量)
                        $inbound = $item->afn_inbound_working_quantity + $item->afn_inbound_shipped_quantity + $item->afn_inbound_receiving_quantity;

                        //总库存 (可用库存+保留库存+在途)
                        $total = $quantity + $inbound;
                        if(($pSkuId == 0) && ($total == 0)){
                            continue;
                        }

                        if(!$pSkuId){
                            $price = 0;
                        }else{
                            if(!array_key_exists($pSkuId,$priceArr)){
                                $pSkuModel = ProductSku::getModelById($pSkuId);
                                $priceArr[$item->psku_id] = ProductSku::getPuPrice($pSkuModel);
                            }
                            $price = $priceArr[$item->psku_id];
                        }

                        //更新erp-FBA每日库存
                        SrFBAInventoryModel::query()->updateOrCreate(
                            [
                                'country_id' => $item->country_id,
                                'seller_sku' => $item->sku,
                            ],
                            [
                                'account_id' => $item->account_id,
                                'area_id' => $areaId,
                                'psku_id' => $pSkuId,
                                'fnsku' => $item->fnsku,
                                'asin' => $item->asin,
                                'total_quantity' => $total, //总库存（可用库存+保留库存+在途）
                                'quantity' => $quantity, //备货提货参考库存 = 可发库存+保留库存
                                'fulfillable_quantity' => $fulfillableQuantity, //可发库存
                                'reserved_quantity' => $reservedQuantity, //保留库存
                                'inbound' => $inbound, //在途库存
                                'amount' => $price * $total, //货值
                            ]
                        );
                    }
                });

            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }
}
